package com.zzl.test.cluster;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * Description：redis分库（自定义路由算法进行集群），代理（网关）-》路由 -》redis服务器
 * Created by 朱正磊 on 2019-09-23 16:34
 */
public class RedisProxy {

    private static List<String> servers = new ArrayList<>();

    static {
        servers.add("127.0.0.1:6379");
        servers.add("127.0.0.1:6380");
        servers.add("127.0.0.1:6381");
    }

    /**
     * description：最简单的代理实现负载均衡
     * user 朱正磊
     * time 2019-09-23 16:57
     * @param args
     */
    public static void main(String[] args) throws IOException {

        //监听端口
        ServerSocket serverSocket = new ServerSocket(19000);

        Socket socket;

        while ((socket = serverSocket.accept()) != null) {
            try {

                while (true) {

                    System.out.println("一个链接....");
                    InputStream inputStream = socket.getInputStream();
                    byte[] request = new byte[1024];
                    inputStream.read(request);

                    //解析请求
                    String req = new String(request);
                    System.out.println("收到请求：");
                    System.out.println(req);

                    String[] params = req.split("\r\n");

                    //获取key的长度
                    int keyLength = Integer.parseInt(params[3].split("\\$")[1]);
                    //根据key的长度取模
                    int mod = keyLength % servers.size();
                    //根据取模结果获取地址
                    String address = servers.get(mod);
                    System.out.println("根据路由算法选择服务器：" + address);

                    String[] serverInfo = address.split(":");
                    //处理请求
                    Socket client = new Socket(serverInfo[0], Integer.parseInt(serverInfo[1]));
                    //将请求写入redis服务器
                    client.getOutputStream().write(request);

                    //返回结果
                    byte[] response = new byte[1024];
                    //将redis服务器内容输出
                    client.getInputStream().read(response);
                    client.close();

                    socket.getOutputStream().write(response);
                    System.out.println("打印结束***************");
                    System.out.println();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
